package com.atguigu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.EduConfig;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * ClassName: DimUtil
 * Package: com.atguigu.gmall.realtime.utils
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/9 19:25
 * @Version 1.0
 */
public class DimUtil {

    public static JSONObject getDimInfo(Connection connection,String tableName,String id) throws Exception {
        //连接redis
        Jedis jedis = JedisUtil.getJedis();
        //从redis中查询维表数据
        String redisKey = "DIM:" + tableName.toUpperCase() +":" + id;
        String dimInfo = jedis.get(redisKey);
        if (dimInfo != null){
            //重置过期时间
            jedis.expire(redisKey,24*3600);
            jedis.close();
            return JSON.parseObject(dimInfo);
        }

        //从Phoenix中读取维表数据
        String sql ="select * from " + EduConfig.HBASE_SCHEMA + "." + tableName + " where id ='" + id + "'";
        System.out.println("查询SQL为：" + sql);
        List<JSONObject> queryList = JdbcUtil.queryList(connection, sql, JSONObject.class, false);
        JSONObject jsonObject = queryList.get(0);
        //写入redis
        jedis.setex(redisKey,24*3600,jsonObject.toJSONString());

        jedis.close();
        return queryList.get(0);

    }

    public static void main(String[] args) throws Exception {
        //
        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();
        JSONObject dimInfo = getDimInfo(connection, "DIM_BASE_CATEGORY_INFO", "1");
        System.out.println(dimInfo.toJSONString());
    }

}
